package com.lanhai.agv.push;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;

/**
 * 第三方心跳发送
 * 
 * @author virus408
 *
 */
public class ThirdHeartThread {
	private boolean running;
	private Thread th;

	public void Start(String ip, int port) {
		running = true;
		th = new Thread() {
			@Override
			public void run() {

				byte step = 1;
				while (running) {
					try {
						ByteArrayOutputStream baos = new ByteArrayOutputStream();
						DataOutputStream dos = new DataOutputStream(baos);
						DatagramSocket ds = new DatagramSocket(0);// 让java随机指定端口
						byte[] buff = new byte[4];
						buff[0] = step;

						dos.write(buff);
						byte[] buf = baos.toByteArray();
						DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress(ip, port));

						ds.send(dp);
						ds.close();
					} catch (Exception e1) {

					}
					if (step >= 100) {
						step = 1;
					} else {
						step++;
					} 
					try {
						Thread.sleep(1000);
					} catch (Exception ex) {

					}
				}
			}

		};
		th.start();
	}

	public void Stop() {
		running = false;
		try {
			th.interrupt();
			th = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
